/**
 * @description 用户实体
 * @author LI
 * @date 2020-11-11 16:03
 */

import {
  BeforeInsert,
  Column,
  CreateDateColumn,
  Entity,
  OneToMany,
  PrimaryGeneratedColumn,
  UpdateDateColumn
} from 'typeorm'
import { IsEmail } from 'class-validator'
import * as argon2 from 'argon2'
import { ArticleEntity } from '../article/article.entity'
import { CommentEntity } from '../comment/comment.entity'

@Entity('li_users')
export class UserEntity {
  @PrimaryGeneratedColumn({ comment: '主键id' })
  id: number

  @Column({ type: 'varchar', length: 50, nullable: true, default: '默认昵称', name: 'nick_name', comment: '昵称' })
  nickName: string

  @Column({ type: 'varchar', length: 50, unique: true, name: 'login_email', comment: '邮箱' })
  @IsEmail({}, { message: '邮箱格式不正确' })
  loginEmail: string

  @Column({ type: 'varchar', length: 255, comment: '密码' })
  password: string

  @BeforeInsert()
  async hashPassword() {
    this.password = await argon2.hash(this.password)
  }

  @Column({ type: 'varchar', name: 'photo_url', length: 255, nullable: true, comment: '头像' })
  photoUrl: string

  @CreateDateColumn()
  @Column({ type: 'datetime', name: 'created_at', comment: '创建时间', default: () => "CURRENT_TIMESTAMP" })
  createdAt: Date

  @CreateDateColumn()
  @UpdateDateColumn()
  @Column({ type: 'datetime', name: 'updated_at', comment: '更新时间', default: () => "CURRENT_TIMESTAMP" })
  updatedAt: Date

  @OneToMany(() => ArticleEntity, article => article.userId)
  articles: ArticleEntity[]

  @OneToMany(() => CommentEntity, comment => comment.userId)
  comments: CommentEntity[]
}